package com.aliyun.gts.sso.boot;

import com.aliyun.gts.sso.filter.SFSSOFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.util.StringUtils;

@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableConfigurationProperties(SFSSOLoginProperties.class)
@Slf4j
public class SFSSOAutoConfiguration {

    private static final String DEFAULT_URI_PATTERNS = "/*";

    private static final String DEFAULT_SSO_FILTER_NAME = "sfSSOFilter";

    @Bean
    @ConditionalOnMissingBean(SFSSOFilter.class)
    @ConditionalOnProperty(name = "sf.sso.login.enabled", havingValue = "true")
    public SFSSOFilter sfSSOFilter() {
        return new SFSSOFilter();
    }

    @Bean
    @ConditionalOnProperty(name = "sf.sso.login.enabled", havingValue = "true")
    public FilterRegistrationBean<SFSSOFilter> gtsSSOFilterRegistrationBean(SFSSOFilter gtsSSOFilter, SFSSOLoginProperties gtsSsoLoginProperties) {
        if (StringUtils.isEmpty(gtsSsoLoginProperties.getHost())) {
            throw new IllegalArgumentException("gts.sso.login.host为空");
        }
        FilterRegistrationBean<SFSSOFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(gtsSSOFilter);
        registration.addUrlPatterns(DEFAULT_URI_PATTERNS);
        registration.setName(DEFAULT_SSO_FILTER_NAME);
        registration.setOrder(Ordered.LOWEST_PRECEDENCE);
        log.info("GtsSSOLoginFilter autoconfigure successfully, gts.sso.login.host:{}", gtsSsoLoginProperties.getHost());
        return registration;
    }
}